import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Offer32III {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root==null){
            return new ArrayList<>();
        }
        Deque<TreeNode> queues = new LinkedList<>();
        queues.add(root);
        List<List<Integer>> result = new ArrayList<>();
        while (!queues.isEmpty()){
            LinkedList<Integer> list = new LinkedList<>();
            for (int i = queues.size(); i >0; i--) {
                TreeNode poll = queues.poll();
                if (result.size()%2==0) list.addLast(poll.val);
                else list.addFirst(poll.val);
                if (poll.left!=null) queues.add(poll.left);
                if (poll.right!=null) queues.add(poll.right);
            }
            result.add(list);
        }
        return result;
    }
}
